import { login } from '@renderer/api/login/index'
import { getPosSaleGoodsList, getFile, getBriefShopList, getPayTypeList, getTareList } from '@renderer/api/common/index'
import { defineStore } from 'pinia'

import { getServerTimeString, getTimeString } from '@renderer/utils';
//@ts-nocheck
// console.log(window.navigator.onLine)
export const useUserStore = defineStore('user', {
  state: () => {
    return {
      isOnline: window.navigator.onLine, //网络状态
      a: 1,
      userInfo: JSON.parse(localStorage.getItem('userInfo') as string) || {},
      allData: JSON.parse(localStorage.getItem('allData') as string) || [], //原数据
      saleGoodsData: JSON.parse(localStorage.getItem('saleGoodsData') as string) || [],  //销售商品数据
      shopID: localStorage.getItem('shopID') || '',
      shopInfo: JSON.parse(localStorage.getItem('shopInfo') as string) || {},
      currentTime: Date.now(),
      weight: '0.000', //重量
      tare: '0.000', //皮重
      shopList: JSON.parse(localStorage.getItem('shopList') as string) || [], //店铺列表
      shoppingCarData: JSON.parse(localStorage.getItem('shoppingCarData') as string) || [[], [], [], []], //购物车数据
      currentActiveVariableIndex: localStorage.getItem('currentActiveVariableIndex') || 0,//当前选择的结算栏 V1 、V2 ... 索引
      payTypeList: JSON.parse(localStorage.getItem('payTypeList') as string) || {},
      quickPayList: JSON.parse(localStorage.getItem('quickPayList') as string) || ['200', '100', '50', '30'],//快捷金额
      tareList: JSON.parse(localStorage.getItem('tareList') as string) || [],//常用皮重
      leftPadding: localStorage.getItem('leftPadding') as any || '0',//打印机左边距xx个字符
      rightPadding: localStorage.getItem('rightPadding') as any || '0',//打印机右边距xx个字符
      account: localStorage.getItem('YSD_ACCOUNT') as string || '',//用户名
      currentScaleType:localStorage.getItem('YSD_SCALETYPE') as string || '1',//当前称类型，默认为寺冈
    }
  },
  getters: {
    timeWithYearString: (state) => getTimeString(state.currentTime),
    timeString: (state) => getServerTimeString(state.currentTime),
    paperLeft: (state) => state.leftPadding * 36 + 'px',//36是字体大小 为36px
    paperRight: (state) => state.rightPadding * 36 + 'px',
  },
  actions: {
    setCurrentScaleType(currentScaleType){
      this.currentScaleType = currentScaleType
      localStorage.setItem('YSD_SCALETYPE', currentScaleType)
    },
    setCurrentTime(currentTime){
      this.currentTime = currentTime
    },
    setAccount(account) {
      this.account = account
      localStorage.setItem('YSD_ACCOUNT', account)
    },
    setLeftPadding(leftPadding) {
      this.leftPadding = leftPadding
      localStorage.setItem('leftPadding', leftPadding)
    },
    setRightPadding(rightPadding) {
      this.rightPadding = rightPadding
      localStorage.setItem('rightPadding', rightPadding)
    },
    setWeight(weight) {
      this.weight = weight
    },
    setTare(tare) {
      this.tare = tare
    },
    setShopID(shopID) {
      this.shopID = shopID
      localStorage.setItem('shopID', shopID)
    },
    setShopInfo(shopInfo) {
     // console.log('setShopInfo', shopInfo)
      this.shopInfo = shopInfo
      localStorage.setItem('shopInfo', JSON.stringify(shopInfo))
    },
    setOnline(status: boolean) {
      this.isOnline = status
    },
    setCurrentActiveVariableIndex(index) {
      this.currentActiveVariableIndex = index
      localStorage.setItem('currentActiveVariableIndex', index)
    },
    setShoppingCarData(shoppingCarData) {//购物车数据
      this.shoppingCarData = shoppingCarData
      localStorage.setItem('shoppingCarData', JSON.stringify(shoppingCarData))
    },
    setQuickPayList(quickPayList) {
      this.quickPayList = quickPayList
      localStorage.setItem('quickPayList', JSON.stringify(quickPayList))
    },
    async toLogin(reqData) {
      const { data } = await login(reqData)
      this.setAccount(reqData.account) //记住用户名
   
     
      // 使用IPC发送服务器时间给主进程
      window.electron.ipcRenderer.send('set-system-time', data.current_time);


      this.userInfo = data
      localStorage.setItem('userInfo', JSON.stringify(data))
      localStorage.setItem('token', data.access_token)


      this.fetchData()




    },
    async fetchData() {
      try {
        // 创建一个 Promise 数组，用于并发执行所有请求
        const requests = [
          getPosSaleGoodsList(this.userInfo.user_organizationId, this.shopID),//获取全部数据
          getFile(this.shopID),//读取文件(视频、图片)
          getBriefShopList(this.userInfo.user_organizationId),//获取简要店铺列表
          getPayTypeList(), //获取付款方式
          getTareList(this.userInfo.user_organizationId) //获取常用皮重
        ];

        // 使用 Promise.allSettled 并发执行所有请求
        const results = await Promise.allSettled(requests);

        // 处理各个请求的结果
        results.forEach((result, index) => {
          // console.log(result)
          // console.log(index)
          if (result.status === 'fulfilled') {
            switch (index) {
              case 0: // getPosSaleGoodsList
                //console.log(result.value)
                const goodsRes = result.value;
                this.allData = goodsRes.data;
                localStorage.setItem('allData', JSON.stringify(goodsRes.data));

                // 获取零售数据
                if (goodsRes.data && goodsRes.data.goodsInfos) {
                  this.saleGoodsData = goodsRes.data.goodsInfos.find(item => item.priceType === 'RP')
                    ?.posSalePanelGoodsVos?.[0]?.posSaleGoodsPriceVos || [];
                  localStorage.setItem('saleGoodsData', JSON.stringify(this.saleGoodsData));
                }
                break;

              case 1: // getFile
                //console.log('File Response:', result.value);
                window.electron.ipcRenderer.send('get-files', result.value.data)
                break;

              case 2: // getBriefShopList
                const shopListRes = result.value;
                this.shopList = shopListRes.data;
                localStorage.setItem('shopList', JSON.stringify(shopListRes.data));
                break;

              case 3: // getPayTypeList
                const payTypeRes = result.value;
                this.payTypeList = payTypeRes.data;
                localStorage.setItem('payTypeList', JSON.stringify(payTypeRes.data));
                break;
              case 4: // getTareList
                const tareListRes = result.value;
                this.tareList = tareListRes.data;
                localStorage.setItem('tareList', JSON.stringify(tareListRes.data));
                break;

              default:
                break;
            }
          } else { // 请求失败的情况
            console.error(`Request ${index + 1} failed with error:`, result.reason);
          }
        });

      } catch (error) {
        console.error("Unexpected error:", error);
      }
    }

  }
})





//   // 调用 fetchData 函数
//   fetchData(data);